﻿namespace ElisVK
{
    using System.Net;
    using System.Windows;
    using System.Windows.Forms;
    using System.Windows.Input;
    using System.Windows.Markup;

    using ElisVK.Controls;
    using ElisVK.Splash;
    using ViewModels;
    using Button = System.Windows.Controls.Button;
    using Panel = System.Windows.Controls.Panel;
    using UserControl = System.Windows.Controls.UserControl;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    [TemplatePart(Name = "PART_WindowHeader", Type = typeof(Panel)),
     TemplatePart(Name = "PART_WindowContent", Type = typeof(Panel)),
     TemplatePart(Name = "PART_Minimize", Type = typeof(Button)),
     TemplatePart(Name = "PART_Maximize", Type = typeof(Button)),
     TemplatePart(Name = "PART_Restore", Type = typeof(Button)),
     TemplatePart(Name = "PART_Close", Type = typeof(Button))]
    public sealed partial class MainWindow
    {
        #region Fields

        private readonly ButtonImages _windowMinimize;
        private readonly ButtonImages _windowMaximize;
        private readonly ButtonImages _windowRestore;
        private readonly ButtonImages _windowClose;

        private Panel _windowHeader;

        private ElisVKViewModel _elisVKViewModel;

        #endregion Fields

        #region Constructors

        public MainWindow(Window window) : this()
        {
            window.Close();
        }

        public MainWindow()
        {
            _windowMinimize = new ButtonImages(
                App.WindowUI.GetImage("BtnWndMinimizeActive.png"),
                App.WindowUI.GetImage("BtnWndMinimizeHover.png"),
                App.WindowUI.GetImage("BtnWndMinimizePressed.png"),
                App.WindowUI.GetImage("BtnWndMinimizeInactive.png"));
            _windowMaximize = new ButtonImages(
                App.WindowUI.GetImage("BtnWndMaximizeActive.png"),
                App.WindowUI.GetImage("BtnWndMaximizeHover.png"),
                App.WindowUI.GetImage("BtnWndMaximizePressed.png"),
                App.WindowUI.GetImage("BtnWndMaximizeInactive.png"));
            _windowRestore = new ButtonImages(
                App.WindowUI.GetImage("BtnWndRestoreActive.png"),
                App.WindowUI.GetImage("BtnWndRestoreHover.png"),
                App.WindowUI.GetImage("BtnWndRestorePressed.png"),
                App.WindowUI.GetImage("BtnWndRestoreInactive.png"));
            _windowClose = new ButtonImages(
                App.WindowUI.GetImage("BtnWndCloseActive.png"),
                App.WindowUI.GetImage("BtnWndCloseHover.png"),
                App.WindowUI.GetImage("BtnWndClosePressed.png"),
                App.WindowUI.GetImage("BtnWndCloseInactive.png"));

            InitializeComponent();
        }

        #endregion Constructors

        #region Properties

        public ButtonImages WindowMinimize
        {
            get
            {
                return _windowMinimize;
            }
        }

        public ButtonImages WindowMaximize
        {
            get
            {
                return _windowMaximize;
            }
        }

        public ButtonImages WindowRestore
        {
            get
            {
                return _windowRestore;
            }
        }

        public ButtonImages WindowClose
        {
            get
            {
                return _windowClose;
            }
        }

        #endregion Properties

        #region Implementation - Template

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            if (_windowHeader != null)
            {
                _windowHeader.MouseLeftButtonDown -= WindowHeader_MouseLeftButtonDown;
            }

            _windowHeader = GetTemplateChild("PART_WindowHeader") as Panel;
            if (_windowHeader != null)
            {
                _windowHeader.MouseLeftButtonDown += WindowHeader_MouseLeftButtonDown;
            }

            var minimizeButton = GetTemplateChild("PART_Minimize") as Button;

            if (minimizeButton != null)
            {
                minimizeButton.DataContext = WindowMinimize;
                minimizeButton.Click += OnMinimizeWindow;
            }

            var maximizeButton = GetTemplateChild("PART_Maximize") as Button;

            if (maximizeButton != null)
            {
                maximizeButton.DataContext = WindowMaximize;
                maximizeButton.Click += OnMaximizeWindow;
            }

            var restoreButton = GetTemplateChild("PART_Restore") as Button;

            if (restoreButton != null)
            {
                restoreButton.DataContext = WindowRestore;
                restoreButton.Click += OnMaximizeWindow;
            }

            var closeButton = GetTemplateChild("PART_Close") as Button;

            if (closeButton != null)
            {
                closeButton.DataContext = WindowClose;
                closeButton.Click += OnCloseWindow;
            }

            var elisVKView = App.WindowUI.GetUserControl("ElisVKView");

            _elisVKViewModel = new ElisVKViewModel(elisVKView, notifyIcon);
            elisVKView.DataContext = _elisVKViewModel;

            IAddChild container = Panel;

            container.AddChild(elisVKView);
        }

        #endregion Implementation - Template

        #region Notify icon handling
        
        private void notifyIcon_TrayMouseDoubleClick(object sender, RoutedEventArgs e)
        {
            if (WindowState == WindowState.Normal || WindowState == WindowState.Maximized)
            {
                Hide();
                ShowInTaskbar = false;
                WindowState = WindowState.Minimized;
            }
            else
            {
                Show();
                ShowInTaskbar = true;
                WindowState = WindowState.Normal;
            }
        }
        
        #endregion Notify icon handling
        
        #region Methods

        private void WindowHeader_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        private void OnMaximizeWindow(object sender, RoutedEventArgs e)
        {
            WindowState = WindowState == WindowState.Maximized ?
                WindowState.Normal : WindowState.Maximized;
        }

        private void OnMinimizeWindow(object sender, RoutedEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }

        private void OnCloseWindow(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Splasher.CloseSplash();
            webBrowser.Navigated += BrowserNavigated;
            webBrowser.Navigate(@"http://api.vkontakte.ru/oauth/authorize?client_id=2707037&scope=audio,friends&redirect_uri=http://api.vkontakte.ru/blank.html&display=page&response_type=token");
        }

        private void BrowserNavigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            var uri = e.Url.AbsoluteUri;

            const string AccessTokenStart = "access_token=";
            const string ExpiresInStart = "expires_in=";
            const string UserIDStart = "user_id=";
            const string RemixSIDStart = "remixsid=";

            int start = uri.IndexOf(AccessTokenStart) + AccessTokenStart.Length;

            if (uri.IndexOf(AccessTokenStart) != -1)
            {
                App.SessionInfo.AccessToken = uri.Substring(start, uri.IndexOf('&', start) - start);

                start = uri.IndexOf(ExpiresInStart) + ExpiresInStart.Length;
                App.SessionInfo.ExpiresIn = int.Parse(uri.Substring(start, uri.IndexOf('&', start) - start));

                start = uri.IndexOf(UserIDStart) + UserIDStart.Length;
                App.SessionInfo.UserID = int.Parse(uri.Substring(start)); ;

                var sid = webBrowser.Document.Cookie;
                start = sid.IndexOf(RemixSIDStart) + RemixSIDStart.Length;
                int end = sid.IndexOf(';', start) == -1 ? sid.Length : sid.IndexOf(';', start);

                sid = sid.Substring(start, end - start);
                App.SessionInfo.Cookie = new Cookie("remixsid", sid) { Domain = "vkontakte.ru" };

                autorizationContainer.Visibility = Visibility.Collapsed;
                Panel.Visibility = Visibility.Visible;
                _elisVKViewModel.RefreshAudioList();
            }
        }

        #endregion Methods
    }
}
